#ifndef HEAP_TIMER_H
#define HEAP_TIMER_H
#include <queue>
#include <unordered_map>
#include <time.h>
#include <algorithm>
#include <arpa/inet.h>
#include <functional>
#include <assert.h>
#include <chrono>
#include "../log/log.h"

typedef std::function<void()> TimeoutCallBack;
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds MS;
typedef Clock::time_point TimeStamp;

struct TimerNode
{
    //定时器的唯一标识，通常对应Web服务器中的连接ID或者任务ID
    //用于在哈希表ref_中建立映射关系
    int id;
    //定时器的过去时间戳，表示定时器何时应该被触发执行
    TimeStamp expire;
    //定时器的回调函数，在定时器超时时，会调用这个函数，没有参数，返回值是void
    TimeoutCallBack cb;
    bool operator<(const TimerNode& t)
    {
        return expire < t.expire;
    }
};
class HeapTimer
{
public:
    HeapTimer(){heap_.reserve(64);}
    ~HeapTimer(){clear();}
    void adjust(int id,int newExpires);
    void add(int id,int timeOut,const TimeoutCallBack& cb);
    void doWork(int id);
    void clear();
    void pop();
    int GetNextTick();
    void tick();
private: 
    void del_(size_t i);
    void siftup_(size_t i);
    bool siftdown_(size_t index,size_t n);
    void SwapNode_(size_t i,size_t j);
    std::vector<TimerNode> heap_;
    std::unordered_map<int,size_t> ref_;
};
#endif